package com.demo.common.interceptor;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;

import com.demo.common.utils.JWTUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 拦截器,从请求头中获取  token ,key就叫 token
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    String token = request.getHeader("token");  //从请求头中获得token
    Map<String, Object> map = new HashMap<>();
    try {
      JWTUtils.verify(token); //验证令牌
      return true;
    } catch (TokenExpiredException e) {
      map.put("code", 401);
      map.put("msg", "Token已经过期!!!");
    } catch (SignatureVerificationException e) {
      map.put("code", 401);
      map.put("msg", "签名错误!!!");
    } catch (AlgorithmMismatchException e) {
      map.put("code", 401);
      map.put("msg", "加密算法不匹配!!!");
    } catch (Exception e) {
      e.printStackTrace();
      map.put("code", 401);
      map.put("msg", "无效token!!!");
    }
    
    return false;
  }
}


